<template>
  <a-modal
    :width="'100%'"
    :style="{ top: 0, paddingBottom: 0 }"
    :bodyStyle="{
      backgroundColor: '#F0F2F5',
      padding: '8px',
      overflow: 'auto'
    }"
    :visible="visible"
    title="data.ranchName"
    :footer="null"
    @update:visible="updateVisible"
  >
    <div class="ele-body ele-body-card ranch-scene-container">
      <!-- 左侧场景区域 -->
      <div class="scene-sidebar">
        <div class="scene-title">场景区域</div>
        <a-menu
          mode="inline"
          theme="dark"
          :inline-collapsed="false"
          class="scene-menu"
          :open-keys="[...expandedBarns, ...expandedAreas]"
          @openChange="onMenuOpenChange"
        >
          <!-- 牛舍列表 -->
          <a-sub-menu v-for="barn in barnList" :key="barn.oxtallId">
            <template #title>
              <a-space>
                <home-outlined />
                <span>{{ barn.oxtallName }}</span>
              </a-space>
            </template>
            
            <!-- 分区列表 -->
            <a-sub-menu v-for="area in barn.areas || []" :key="area.id" @click="handleAreaClick(area.id, barn.oxtallId)">
              <template #title>
                <a-space>
                  <partition-outlined />
                  <span>{{ area.name }}</span>
                </a-space>
              </template>
              
              <!-- 相机列表 -->
              <a-menu-item 
                v-for="camera in area.cameras || []" 
                :key="camera.id"
                @click="handleCameraClick(camera.id, area.id, barn.oxtallId)"
              >
                <div class="camera-menu-item">
                  <div class="camera-badge" :class="camera.recordStatus == 1 ? 'online' : 'offline'">
                    {{ camera.recordStatus == 1 ? '在线' : '离线' }}
                  </div>
                  <div class="camera-name">{{ camera.name }}</div>
                </div>
              </a-menu-item>
            </a-sub-menu>
          </a-sub-menu>
        </a-menu>
      </div>
      
      <!-- 右侧相机预览区域 -->
      <div class="camera-preview-area">
        <div class="camera-grid">
          <div 
            v-for="(camera, index) in getSelectedCameras()" 
            :key="camera.id"
            class="camera-preview-item"
          >
            <div class="camera-preview-item">
              <div class="camera-preview-header">
                <span class="camera-id">{{ camera.name }}</span>
                <div class="camera-controls">
                  <a-button 
                    type="text" 
                    size="small"
                    @click="toggleCameraRefresh(camera.id)"
                  >
                    <template #icon>
                      <pause-circle-outlined v-if="cameraRefreshStates[camera.id]" />
                      <play-circle-outlined v-else />
                    </template>
                  </a-button>
                  <a-button type="text" size="small" @click="refreshCamera(camera.id)">
                    <template #icon><reload-outlined /></template>
                  </a-button>
                  <a-button type="text" size="small">
                    <template #icon><fullscreen-outlined /></template>
                  </a-button>
                  <a-button type="text" size="small" @click="removeCamera(camera.id)">
                    <template #icon><close-outlined /></template>
                  </a-button>
                </div>
              </div>
              <div class="camera-preview-content">
                <canvas :ref="'canvas-' + camera.id" class="camera-canvas"></canvas>
              </div>
              <div class="camera-preview-footer">
                <div class="camera-info">
                  <span>清晰度: {{ clarityLevel }}%</span>
                  <span>缩放比: {{ zoomLevel }}%</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </a-modal>
</template>

<script>
import { 
  HomeOutlined, 
  DownOutlined, 
  ReloadOutlined, 
  FullscreenOutlined, 
  CloseOutlined,
  PartitionOutlined,
  PlayCircleOutlined, 
  PauseCircleOutlined
} from '@ant-design/icons-vue';
import { message } from 'ant-design-vue';
import { OxtallApi } from '@/api/property/OxtallApi';
import { DeviceSprayCameraGroupApi } from '@/api/property/spraycamera/DeviceSprayCameraGroupApi';
import { DeviceSprayCameraApi } from '@/api/property/spraycamera/DeviceSprayCameraApi';
import { DeviceSprayCameraCaptureimgApi } from '@/api/property/spraycamera/DeviceSprayCameraCaptureimgApi';
import { DeviceSprayCameraSlotApi } from '@/api/property/spraycamera/DeviceSprayCameraSlotApi';
import {DeviceCommandDownQueueApi} from "@/api/property/DeviceCommandDownQueueApi";
export default {
  name: 'DeviceManagerdeviceCameraRanchScene',
  components: {
    HomeOutlined,
    DownOutlined,
    ReloadOutlined,
    FullscreenOutlined,
    CloseOutlined,
    PartitionOutlined,
    PlayCircleOutlined,
    PauseCircleOutlined,
  },
  emits: ['done', 'update:visible'],
  props: {
    // 弹窗是否打开
    visible: Boolean,
    // 菜单数据
    data: Object
  },
  async mounted() {
    await this.fetchBarnList();
  },
  async created() {

  },
  data() {
    return {
      barnList: [],
      expandedBarns: [], // 存储展开的牛舍ID
      expandedAreas: [], // 存储展开的分区ID
      selectedCameras: [],
      loading: false,
      statusOptions: ['normal', 'warning'],
      actionOptions: ['上料', '饲喂等', '精准饲喂', '精准补料'],
      stateOptions: ['上料', '未上料', '下料', '未下料'],
      cameraRefreshStates: {}, // 存储每个相机的刷新状态
      cameraRefreshIntervals: {}, // 存储每个相机的定时器
      clarityLevel: '50',
      zoomLevel: '50',
      withAnnotation: '1',
      withDetection: '1',
      withTimestamp: '0',
      refreshInterval: 60000, // 刷新间隔，30秒
      originalImage: null,
      ORIGINAL_WIDTH: 1920,
      ORIGINAL_HEIGHT: 1080,
      displayScale: 1,
    };
  },
  // 添加 unmounted 生命周期钩子
  unmounted() {
    this.clearAllCameraIntervals();
  },

  methods: {
    // 修改 updateVisible 方法
    updateVisible(value) {
      if (!value) {
        // modal关闭时清理所有定时任务
        this.clearAllCameraIntervals();
      }
      this.$emit('update:visible', value);
    },

    // 添加清理定时器的方法
    clearAllCameraIntervals() {
      Object.keys(this.cameraRefreshIntervals).forEach(cameraId => {
        if (this.cameraRefreshIntervals[cameraId]) {
          clearInterval(this.cameraRefreshIntervals[cameraId]);
          delete this.cameraRefreshIntervals[cameraId];
        }
      });
      // 重置刷新状态
      this.cameraRefreshStates = {};
    },
    
    // 获取牛舍列表
    async fetchBarnList() {
      try {
        this.loading = true;
        const result = await OxtallApi.list({"orgId": this.data.ranchId});
        this.barnList = (result ? result.data : null) || [];
        
        // 只处理第一个牛舍
        if (this.barnList.length > 0) {
          const firstBarn = this.barnList[0];
          this.expandedBarns = [firstBarn.oxtallId];
          await this.fetchAreas(firstBarn.oxtallId, true);
        }
        this.loading = false;
      } catch (error) {
        console.error('获取牛舍列表失败:', error);
        message.error('获取牛舍列表失败');
        this.loading = false;
      }
    },
    
    // 修改 fetchAreas 方法
    async fetchAreas(barnId, isFirstBarn = false) {
      try {
        const result = await DeviceSprayCameraGroupApi.list({"oxtallId": barnId});
        const groups = result || [];
        const areas = groups.map(group => ({
          id: group.groupId,
          name: group.groupName,
          cameras: []
        }));
        
        // 更新牛舍的分区数据
        const barnIndex = this.barnList.findIndex(barn => barn.oxtallId === barnId);
        if (barnIndex !== -1) {
          this.barnList[barnIndex].areas = areas;
          
          // 如果是第一个牛舍，加载第一个分区的相机
          if (isFirstBarn && areas.length > 0) {
            this.expandedAreas = [areas[0].id];
            await this.fetchCameras(areas[0].id, barnId);
          }
        }
      } catch (error) {
        console.error(`获取牛舍${barnId}的分区列表失败:`, error);
        message.error('获取分区列表失败');
      }
    },
    
    // 修改 fetchCameras 方法
    async fetchCameras(areaId, barnId) {
      try {
        // 清空当前选中的相机列表和刷新状态
        this.selectedCameras = [];
        Object.keys(this.cameraRefreshIntervals).forEach(cameraId => {
          clearInterval(this.cameraRefreshIntervals[cameraId]);
        });
        this.cameraRefreshIntervals = {};
    
        const result = await DeviceSprayCameraApi.recordsByGroup({"groupId": areaId});
        const cameras = result || [];
        
        // 格式化相机数据
        const formattedCameras = cameras.map(camera => ({
          id: camera.recordId,
          name: camera.macId + (camera.lable1 ? ("[" + camera.lable1 + "]") : ""),
          recordStatus: camera.recordStatus,
          streamUrl: camera.capImg,
          deviceInfo: camera
        }));
        
        // 更新相机列表
        const barnIndex = this.barnList.findIndex(barn => barn.oxtallId === barnId);
        if (barnIndex !== -1) {
          const areaIndex = this.barnList[barnIndex].areas.findIndex(area => area.id === areaId);
          if (areaIndex !== -1) {
            this.barnList[barnIndex].areas[areaIndex].cameras = formattedCameras;
            
            // 选中所有相机并开始刷新
            formattedCameras.forEach(camera => {
              this.selectedCameras.push(camera.id);
              this.$nextTick(() => {
                // 设置刷新状态为开启
                this.cameraRefreshStates[camera.id] = true;
                // 启动定时刷新
                this.startCameraRefresh(camera.id);
              });
            });
          }
        }
      } catch (error) {
        console.error('获取相机列表失败:', error);
        message.error('获取相机列表失败');
      }
    },
    
    // 切换牛舍展开/收起状态
    toggleBarn(barnId) {
      const index = this.expandedBarns.indexOf(barnId);
      if (index > -1) {
        // 已展开，收起
        this.expandedBarns.splice(index, 1);
        
        // 同时收起该牛舍下的所有分区
        const barn = this.getBarnById(barnId);
        if (barn && barn.areas) {
          barn.areas.forEach(area => {
            const areaIndex = this.expandedAreas.indexOf(area.id);
            if (areaIndex > -1) {
              this.expandedAreas.splice(areaIndex, 1);
            }
          });
        }
      } else {
        // 未展开，展开并获取分区列表
        this.expandedBarns.push(barnId);
        
        // 获取该牛舍的分区列表
        const barn = this.getBarnById(barnId);
        if (barn && (!barn.areas || barn.areas.length === 0)) {
          this.fetchAreas(barnId);
        }
      }
    },
    
    // 切换分区展开/收起状态
    toggleArea(areaId, barnId) {
      const index = this.expandedAreas.indexOf(areaId);
      if (index > -1) {
        // 已展开，收起
        this.expandedAreas.splice(index, 1);
      } else {
        // 未展开，展开并获取相机列表
        this.expandedAreas.push(areaId);
        
        // 清空当前选中的相机列表
        this.selectedCameras = [];
        
        // 获取该分区的相机列表
        const barn = this.getBarnById(barnId);
        if (barn && barn.areas) {
          const area = barn.areas.find(a => a.id === areaId);
          if (area) {
            if (!area.cameras || area.cameras.length === 0) {
              // 如果没有相机数据，获取新数据
              DeviceSprayCameraApi.recordsByGroup({"groupId" : areaId}).then(result => {
                let cameras = result || [];
                const formattedCameras = cameras.map(camera => ({
                  id: camera.recordId,
                  name: camera.macId + (camera.lable1 ? ("[" + camera.lable1 + "]") : ""),
                  recordStatus: camera.recordStatus,
                  streamUrl: camera.capImg,
                  deviceInfo: camera
                }));
                
                // 更新相机列表
                area.cameras = formattedCameras;
                
                // 将所有相机添加到选中列表
                formattedCameras.forEach(camera => {
                  this.selectedCameras.push(camera.id);
                });
                
                // 初始化每个相机的刷新状态和开始刷新
                this.$nextTick(() => {
                  formattedCameras.forEach(camera => {
                    this.cameraRefreshStates[camera.id] = true;
                    this.refreshCamera(camera.id);
                  });
                });
              });
            } else {
              // 如果已有相机数据，直接使用
              area.cameras.forEach(camera => {
                this.selectedCameras.push(camera.id);
                this.cameraRefreshStates[camera.id] = true;
                this.$nextTick(() => {
                  this.refreshCamera(camera.id);
                });
              });
            }
          }
        }
      }
    },
    
    getBarnById(barnId) {
      return this.barnList.find(barn => barn.oxtallId === barnId) || {};
    },
    
    toggleCamera(cameraId) {
      const index = this.selectedCameras.indexOf(cameraId);
      if (index > -1) {
        this.selectedCameras.splice(index, 1);
      } else {
        this.selectedCameras.push(cameraId);
      }
    },
    
    removeCamera(cameraId) {
      const index = this.selectedCameras.indexOf(cameraId);
      if (index > -1) {
        this.selectedCameras.splice(index, 1);
      }
    },
    
    getSelectedCameras() {
      const cameras = [];
      this.barnList.forEach(barn => {
        if (barn.areas) {
          barn.areas.forEach(area => {
            if (area.cameras) {
              area.cameras.forEach(camera => {
                if (this.selectedCameras.includes(camera.id)) {
                  cameras.push(camera);
                }
              });
            }
          });
        }
      });
      return cameras;
    },
    
    getRandomStatus() {
      return this.statusOptions[Math.floor(Math.random() * this.statusOptions.length)];
    },
    
    getRandomAction() {
      return this.actionOptions[Math.floor(Math.random() * this.actionOptions.length)];
    },
    
    getRandomState() {
      return this.stateOptions[Math.floor(Math.random() * this.stateOptions.length)];
    },
    
    // 处理牛舍菜单展开变化
    onBarnOpenChange(openKeys) {
      // 获取新打开的牛舍ID
      const newOpenKeys = openKeys.filter(key => !this.expandedBarns.includes(key));
      
      // 如果有新打开的牛舍，加载其分区数据
      if (newOpenKeys.length > 0) {
        newOpenKeys.forEach(barnId => {
          const barn = this.getBarnById(barnId);
          if (barn && (!barn.areas || barn.areas.length === 0)) {
            this.fetchAreas(barnId);
          }
        });
      }
      
      // 更新展开状态
      this.expandedBarns = openKeys;
    },
    
    // 处理菜单展开变化
    onMenuOpenChange(openKeys) {
      // 区分牛舍ID和分区ID
      const barnKeys = openKeys.filter(key => this.barnList.some(barn => barn.oxtallId === key));
      const areaKeys = openKeys.filter(key => !barnKeys.includes(key));

       // 如果有新打开的牛舍，加载其分区数据
      const newBarnKeys = barnKeys.filter(key => !this.expandedBarns.includes(key));

       // 更新展开状态
      this.expandedBarns = barnKeys;
      this.expandedAreas = areaKeys;
     
      if (newBarnKeys.length > 0) {
        newBarnKeys.forEach(barnId => {
          const barn = this.getBarnById(barnId);
          if (barn) {
            this.fetchAreas(barnId);
          }
        });
      }
    },
    
      // 处理分区点击
      handleAreaClick(areaId, barnId) {
        // 清空当前选中的相机列表
        this.selectedCameras = [];
        Object.keys(this.cameraRefreshIntervals).forEach(cameraId => {
          clearInterval(this.cameraRefreshIntervals[cameraId]);
        });
        this.cameraRefreshIntervals = {};
        
        // 获取该分区的相机列表
        const barn = this.getBarnById(barnId);
        if (barn && barn.areas) {
          const area = barn.areas.find(a => a.id === areaId);
          if (area) {
            // 不管是否有相机数据，都重新获取
            this.fetchCameras(areaId, barnId).then(() => {
              // 获取相机数据后，确保所有相机都被选中并开始渲染
              const currentArea = this.getBarnById(barnId)?.areas?.find(a => a.id === areaId);
              if (currentArea?.cameras) {
                currentArea.cameras.forEach(camera => {
                  if (!this.selectedCameras.includes(camera.id)) {
                    this.selectedCameras.push(camera.id);
                  }
                  // 确保在下一个渲染周期初始化相机
                  this.$nextTick(() => {
                    this.cameraRefreshStates[camera.id] = true;
                    this.refreshCamera(camera.id);
                  });
                });
              }
            });
          }
        }
        
        // 阻止事件冒泡
        event?.stopPropagation();
      },
    
      // 处理相机点击
      handleCameraClick(cameraId, areaId, barnId) {
        // 清空当前选中的相机列表
        this.selectedCameras = [];
        
        // 获取最新的相机数据
        const barn = this.getBarnById(barnId);
        if (barn && barn.areas) {
          const area = barn.areas.find(a => a.id === areaId);
          if (area?.cameras) {
            const camera = area.cameras.find(c => c.id === cameraId);
            if (camera) {
              // 只添加当前点击的相机
              this.selectedCameras.push(cameraId);
              
              // 确保在下一个渲染周期初始化相机
              this.$nextTick(() => {
                this.cameraRefreshStates[cameraId] = true;
                this.refreshCamera(cameraId);
              });
            }
          }
        }
        
        // 阻止事件冒泡
        event?.stopPropagation();
      },

      // 添加新方法
      startCameraRefresh(cameraId) {
        // 先清除已存在的定时器
        if (this.cameraRefreshIntervals[cameraId]) {
          clearInterval(this.cameraRefreshIntervals[cameraId]);
        }
         // 立即执行一次刷新
        this.refreshCamera(cameraId);
        // 设置新的定时器
        this.cameraRefreshIntervals[cameraId] = setInterval(() => {
          this.refreshCamera(cameraId);
        }, this.refreshInterval);
      },

      // 修改 toggleCameraRefresh 方法
      toggleCameraRefresh(cameraId) {
        this.cameraRefreshStates[cameraId] = !this.cameraRefreshStates[cameraId];
        
        if (this.cameraRefreshStates[cameraId]) {
          this.startCameraRefresh(cameraId);
        } else {
          if (this.cameraRefreshIntervals[cameraId]) {
            clearInterval(this.cameraRefreshIntervals[cameraId]);
            delete this.cameraRefreshIntervals[cameraId];
          }
        }
      },

      pushCaptureImageAction(recordId) {
        let updateDataRecord = {
          updateData: JSON.stringify({
            old: '',
            update: {
              config : {
                scale : 50,
                quality : 50,
                marks: this.withAnnotation,
                check: this.withDetection,
                time: this.withTimestamp
              }
            }
          }),
          recordId: recordId,
          templateCode: 'spraycamera',
          dictate : 7,
          sceneDictate : 7
        };
        let result = DeviceCommandDownQueueApi.add(updateDataRecord);
        result
          .then(result => {
      
          })
          .catch(() => {
    
          });
      },

      // 修改 refreshCamera 方法
      async refreshCamera(cameraId) {
        try {
          const camera = this.getSelectedCameras().find(c => c.id === cameraId);
          if (!camera || !camera.deviceInfo || !camera.deviceInfo.recordId) {
            console.warn('相机信息不完整:', cameraId);
            return;
          }

          // 获取最新图片
          const response = await DeviceSprayCameraCaptureimgApi.findLastOne(camera.deviceInfo.recordId);
          const imageUrl = response?.data?.imgUrl || camera.streamUrl;
          
          if (!imageUrl) {
            console.warn('未获取到相机图像URL');
            return;
          }

          this.pushCaptureImageAction(camera.deviceInfo.recordId);

          const img = new Image();
          img.crossOrigin = "anonymous";
          
          img.onload = () => {
            const canvas = this.$refs[`canvas-${cameraId}`];
            if (!canvas?.[0]) {
              console.warn('未找到Canvas元素:', cameraId);
              return;
            }

            const ctx = canvas[0].getContext('2d');
            const container = canvas[0].parentElement;
            
            // 设置画布尺寸为容器尺寸
            canvas[0].width = container.clientWidth;
            canvas[0].height = container.clientHeight;
            
            // 计算图片缩放比例，使图片填满整个画布
            const scaleX = container.clientWidth / img.width;
            const scaleY = container.clientHeight / img.height;
            const scale = Math.min(scaleX, scaleY);
            
            // 计算居中位置（如果有需要）
            const x = (container.clientWidth - img.width * scale) / 2;
            const y = (container.clientHeight - img.height * scale) / 2;
            
            // 清空画布
            ctx.clearRect(0, 0, canvas[0].width, canvas[0].height);
            
            // 绘制图片，填满整个画布
            ctx.drawImage(
              img,
              0, 0,
              container.clientWidth,
              container.clientHeight
            );
            
            // 更新缩放比例用于标注
            this.displayScale = scale;
            // 更新显示的缩放比例
            this.zoomLevel = Math.round((container.clientWidth / this.ORIGINAL_WIDTH) * 100);
            
            // 绘制标注
            this.drawAnnotations(ctx, camera.deviceInfo.recordId);
          };

          img.onerror = (error) => {
            console.error('图片加载失败:', imageUrl, error);
          };

          img.src = imageUrl;
        } catch (error) {
          console.error('刷新相机失败:', error);
        }
      },
      
      async drawAnnotations(ctx, recordId) {
        try {
          // 获取标注数据
          let list = await DeviceSprayCameraSlotApi.list({"recordId": recordId});
          if (!list.data || list.data.length === 0) return;

          // 获取画布和容器信息
          const canvasEl = this.$refs[`canvas-${recordId}`];
          if (!canvasEl?.[0]) return;
          
          const container = canvasEl[0].parentElement;
          const canvas = canvasEl[0];
          
          // 计算图片在画布中的实际位置和大小
          const scaleX = container.clientWidth / this.ORIGINAL_WIDTH;
          const scaleY = container.clientHeight / this.ORIGINAL_HEIGHT;
          const scale = Math.min(scaleX, scaleY);
          
          // 计算图片在画布中的偏移量
          const offsetX = (canvas.width - (this.ORIGINAL_WIDTH * scale)) / 2;
          const offsetY = (canvas.height - (this.ORIGINAL_HEIGHT * scale)) / 2;

          // 遍历所有标注并绘制
          list.data.forEach(item => {
            try {
              let pointObj = JSON.parse(item.point) || {};
              if (!pointObj.points || pointObj.points.length !== 4) return;

              this.drawBox(ctx, {
                points: pointObj.points,
                relayid: item.relayid,
                relaySwitch: item.wifirelayDTO?.relaySwitch || 1,
                status: item.wifirelayDTO?.status || 1,
                link: item.wifirelayDTO?.link || 1
              }, scale, offsetX, offsetY);
            } catch (e) {
              console.error('解析标注数据失败:', e);
            }
          });
        } catch (error) {
          console.error('加载标注数据失败:', error);
        }
      },

      // 修改绘制单个标注框方法
      drawBox(ctx, box, scale, offsetX, offsetY) {
        if (!ctx || !box.points || box.points.length !== 4) return;

        ctx.beginPath();
        ctx.strokeStyle = box.link === 2 ? '#52c41a' : '#FF4D4F';
        ctx.lineWidth = 2;

        // 将1080P坐标转换为当前显示坐标
        const displayPoints = box.points.map(point => [
          point[0] * scale + offsetX,
          point[1] * scale + offsetY
        ]);
        const points = displayPoints;
        
        // 计算标注框宽度
        const boxWidth = Math.abs(points[3][0] - points[0][0]);

        // 绘制矩形框
        ctx.moveTo(points[0][0], points[0][1]);
        for (let i = 1; i < points.length; i++) {
          ctx.lineTo(points[i][0], points[i][1]);
        }
        ctx.lineTo(points[0][0], points[0][1]);
        ctx.stroke();

        // 设置更小的字体大小
        const fontSize = '12px Arial';
        ctx.font = fontSize;

        // 第一行：设备ID
        ctx.fillStyle = '#1890ff';
        ctx.fillRect(points[0][0], points[0][1] - 80, boxWidth, 20);
        ctx.fillStyle = '#fff';
        ctx.fillText(
          `${box.relayid}`,
          points[0][0] + 5,
          points[0][1] - 65
        );

        // 第二行：连接状态
        ctx.fillStyle = box.link === 2 ? '#52c41a' : '#FF4D4F';
        ctx.fillRect(points[0][0], points[0][1] - 60, boxWidth, 20);
        ctx.fillStyle = '#fff';
        ctx.fillText(
          box.link === 2 ? "已连" : "断连",
          points[0][0] + 5,
          points[0][1] - 45
        );

        // 第三行：喷淋状态
        let sprayColor;
        switch (box.relaySwitch) {
          case 1:
            sprayColor = '#ff4d4f';  // 喷淋关闭 - 红色
            break;
          case 2:
            sprayColor = '#52c41a';  // 喷淋开启 - 绿色
            break;
          case 3:
            sprayColor = '#faad14';  // 喷淋等待 - 黄色
            break;
          case 4:
            sprayColor = '#ff4d4f';  // 喷淋失败 - 红色
            break;
          default:
            sprayColor = '#d9d9d9';  // 未知状态 - 灰色
        }
        ctx.fillStyle = sprayColor;
        ctx.fillRect(points[0][0], points[0][1] - 40, boxWidth, 20);
        ctx.fillStyle = '#fff';
        const sprayStatus = this.getSprayStatus(box.relaySwitch);
        ctx.fillText(
          sprayStatus.text,
          points[0][0] + 5,
          points[0][1] - 25
        );

        // 第四行：识别状态
        ctx.fillStyle = box.status === 2 ? '#52c41a' : '#FF4D4F';
        ctx.fillRect(points[0][0], points[0][1] - 20, boxWidth, 20);
        ctx.fillStyle = '#fff';
        ctx.fillText(
          box.status === 2 ? "识别到牛" : "未识别",
          points[0][0] + 5,
          points[0][1] - 5
        );
      },
      
    
      // 获取喷淋状态
      getSprayStatus(status) {
        const statusMap = {
          1: { color: '#ff4d4f', text: '喷淋关闭' },
          2: { color: '#52c41a', text: '喷淋开启' },
          3: { color: '#faad14', text: '等待喷淋' },
          4: { color: '#ff4d4f', text: '喷淋失败' }
        };
        return statusMap[status] || { color: '#d9d9d9', text: '未知状态' };
      },

    }
};
</script>
<style scoped>
:deep(.ant-modal-content) {
  min-height: 600px; /* 设置最小高度 */
  height: auto; /* 允许自动拉伸 */
  max-height: 100vh; /* 最大不超过视窗高度 */
  border-radius: 0;
}

:deep(.ant-modal-body) {
  min-height: 490px; /* 设置最小高度 = 600px - 110px */
  height: auto; /* 允许自动拉伸 */
  max-height: calc(100vh - 110px); /* 最大不超过视窗高度减去头部和底部 */
}

.ranch-scene-container {
  display: flex;
  min-height: 490px; /* 与modal-body一致 */
  height: 100%;
}

.scene-sidebar {
  width: 280px;  /* 原来是240px，增加到280px */
  background-color: #1e1e1e;
  color: #fff;
  border-right: 1px solid #333;
  overflow-y: auto;
}

.scene-title {
  padding: 10px 16px;
  font-size: 16px;
  font-weight: bold;
  border-bottom: 1px solid #333;
}

/* 菜单样式优化，使其更紧凑 */
:deep(.scene-menu) {
  background-color: #1e1e1e;
}

:deep(.ant-menu-dark) {
  background-color: #1e1e1e;
}

:deep(.ant-menu-submenu-title) {
  padding: 4px 16px !important;
  height: auto !important;
  line-height: 1.5 !important;
}

/* 修改菜单项样式 */
:deep(.ant-menu-item) {
  padding: 4px 16px !important;
  height: auto !important;
  line-height: 1.5 !important;
  margin: 0 !important;
  display: flex !important;
  align-items: center !important;
}

.camera-menu-item {
  display: flex;
  align-items: center;
  gap: 8px;
  width: 100%;
}

.camera-badge {
  min-width: 40px;
  padding: 1px 4px;
  border-radius: 2px;
  font-size: 12px;
  text-align: center;
  flex-shrink: 0;
}

.camera-badge.online {
  background-color: #52c41a;
  color: #fff;
}

.camera-badge.offline {
  background-color: #ff4d4f;
  color: #fff;
}

.camera-name {
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  color: #fff;
}

@keyframes pulse {
  0% {
    transform: scale(1);
    opacity: 1;
  }
  100% {
    transform: scale(1.5);
    opacity: 0;
  }
}

/* 其他样式保持不变 */
.camera-preview-area {
  flex: 1;
  padding: 16px;
  overflow-y: auto;
}

.camera-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 16px;
}

.camera-preview-item {
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  overflow: hidden;
  background-color: #000;
}

.camera-preview-header {
  background-color: #1890ff;
  color: #fff;
  padding: 4px 8px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.camera-controls {
  display: flex;
}

.camera-preview-content {
  position: relative;
  height: 360px;
  background-color: #000;
  display: flex;
  align-items: center;
  justify-content: center;
}

.camera-canvas {
  max-width: 100%;
  max-height: 100%;
  width: auto;
  height: auto;
  object-fit: contain;
}

.camera-preview-footer {
  background-color: #f0f0f0;
  padding: 4px 8px;
}

.camera-info {
  display: flex;
  justify-content: space-between;
}

.camera-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  pointer-events: none;
}

.grid-container {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  grid-template-rows: repeat(2, 1fr);
  height: 100%;
  width: 100%;
}

.grid-item {
  border: 2px solid #52c41a;
  padding: 4px;
  display: flex;
  flex-direction: column;
  color: white;
  font-size: 12px;
}

.grid-number {
  background-color: #52c41a;
  padding: 2px 4px;
  width: fit-content;
}

.grid-status {
  margin-top: 4px;
  padding: 2px 4px;
  width: fit-content;
}

.grid-status.normal {
  background-color: #52c41a;
}

.grid-status.warning {
  background-color: #ff4d4f;
}

.grid-actions {
  margin-top: auto;
  display: flex;
  justify-content: space-between;
}
.camera-canvas {
  max-width: 100%;
  max-height: 100%;
  width: auto;
  height: auto;
}
</style>
